package com.weiyi.portal.controller;

import com.weiyi.common.common.api.CommonResult;
import com.weiyi.common.common.util.JwtTokenUtil;
import com.weiyi.portal.modules.ums.model.UmsMember;
import com.weiyi.portal.modules.ums.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Autowired
    UmsMemberService umsMemberService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;


    /**
     * 登录
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CommonResult login(@Validated @RequestBody UmsMember user, HttpSession session){
        UmsMember member = umsMemberService.login(user.getUsername(), user.getPassword());
        if(member==null){
            return CommonResult.validateFailed("用户名或密码错误");
        }

        String token = jwtTokenUtil.generateUserNameStr(member.getUsername());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        tokenMap.put("tokenHeader",tokenHeader);
        tokenMap.put("sessionID", session.getId());
        session.setAttribute("user", user);
        // jwt
        return CommonResult.success(tokenMap);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public CommonResult register(@Validated @RequestBody UmsMember user){
        UmsMember register = umsMemberService.register(user);
        if(register==null){
            return CommonResult.failed();
        }
        return CommonResult.success(register);
    }


}
